package com.ssy.lingxi.system.handler.converter;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.platform.manage.api.model.dto.onlineservice.ParamConfigDTO;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.ArrayList;
import java.util.List;

/**
 * 在线客服参数配置与jsonb相互转换类
 * @author wyx
 * @version 2.0.0
 * @date 2021-11-16
 */
@Converter(autoApply = true)
public class JpaJsonToParamConfigConverter implements AttributeConverter<List<ParamConfigDTO>, String> {
    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public JpaJsonToParamConfigConverter() {
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Override
    public String convertToDatabaseColumn(List<ParamConfigDTO> attribute) {
        try {
            return OBJECT_MAPPER.writeValueAsString(attribute);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"在线客服实体转换Json错误");
        }
    }

    @Override
    public List<ParamConfigDTO> convertToEntityAttribute(String dbData) {
        try {
            if(dbData == null) {
                return new ArrayList<>();
            }

            return OBJECT_MAPPER.readValue(dbData, new TypeReference<List<ParamConfigDTO>>() {});
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"数据库json字段转换在线客服实体错误");
        }
    }
}
